//
//  UIImage+Canvas.m
//  高仿暴走斗图
//
//  Created by huangsongyao on 16/3/7.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "UIImage+Canvas.h"
#import "UIView+Frame.h"

@implementation UIImage (Canvas)

static UIImage *createImageWithColor(UIColor *color, CGRect rect) {
    
    UIGraphicsBeginImageContext(rect.size);//规定一个画布size
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);//画出一个image
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();//获取新的image
    UIGraphicsEndImageContext();
    
    return theImage;
}

+ (UIImage *)createImgWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIImage *image = createImageWithColor(color, rect);
    
    return image;
}

+ (UIImage *)createImgWithColor:(UIColor *)color rect:(CGRect)rect {
    
    UIImage *image = createImageWithColor(color, rect);
    return image;
}

+ (UIImage *)captureImageInView:(UIView *)view {
    
    UIGraphicsBeginImageContextWithOptions(view.viewSize, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;
}

+ (UIImage *)drawQRCodeBackgroundImageWithReferenceRect:(CGRect)referenceRect cropRect:(CGRect)cropRect alpha:(CGFloat)alpha {
    
    CGSize referenceSize = CGSizeMake(CGRectGetWidth(referenceRect), CGRectGetHeight(referenceRect));
    
    UIGraphicsBeginImageContext(referenceSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetRGBFillColor(context, 0.27, 0.27, 0.27, alpha);
    CGSize screenSize =[UIScreen mainScreen].bounds.size;
    CGRect drawRect =CGRectMake(0, 0, screenSize.width,screenSize.height);
    
    CGContextFillRect(context, drawRect);
    
    drawRect = CGRectMake(cropRect.origin.x-referenceRect.origin.x, cropRect.origin.y-referenceRect.origin.y, cropRect.size.width, cropRect.size.height);
    CGContextClearRect(context, drawRect);
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}


@end
